07. Exercise: Creating the SleepNight Entity
L6 09 Creating The NightData SC
Now it’s your turn to complete this exercise yourself.
In this step you'll be creating a data class to define the sleep data entity.
In the
databasepackage, find and open theSleepNight.ktfile.Create the
SleepNightdata class with parameters for an ID, start time and end time in milliseconds, and a numerical sleep quality rating:
data class SleepNight (
var nightId: Long = 0L,
val startTimeMilli: Long = System.currentTimeMillis(),
var endTimeMilli: Long = startTimeMilli,
var sleepQuality: Int = -1
)
Annotate the data class with
@Entity, and name the tabledaily_sleep_quality_table.(Remember to perform the necessary imports for this and all the following annotations.)
@Entity(tableName = "daily_sleep_quality_table")
Identify the
nightIdas the primary key by annotating it with@PrimaryKey, and set theautoGenerateparameter totrue:@PrimaryKey(autoGenerate = true)Annotate the remaining properties with
@ColumnInfoand customize their names as shown below.Your finished code should look like this:
@Entity(tableName = "daily_sleep_quality_table")
data class SleepNight(
@PrimaryKey(autoGenerate = true)
var nightId: Long = 0L,
@ColumnInfo(name = "start_time_milli")
val startTimeMilli: Long = System.currentTimeMillis(),
@ColumnInfo(name = "end_time_milli")
var endTimeMilli: Long = startTimeMilli,
@ColumnInfo(name = "quality_rating")
var sleepQuality: Int = -1
)
- Build and run your code to make sure it has no errors.
If you want to start at this step, you can download this exercise from: Step.01-Exercise-Create-Night-Data-Entity.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here: Step.01-Solution-Create-Night-Data-Entity, or using this git diff.
Task Description:
Complete these tasks to add a SleepNight entity to your app.
Task Feedback:
Great! Now you're ready to create the Room database!
Reference documentation
- Defining data using Room entities
- ColumnInfo
- How to auto-generate a unique key
- List of all Room annotations